package com.hispot.projection.bluetooth;

import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;

import java.io.UnsupportedEncodingException;
import java.util.Set;


/**
 * Created by sunray on 2017-7-21.
 */

public class BluetoothClientService extends Service {
    public String TAG = "BluetoothClientService";
    public static boolean IS_CONNECTED = false;
    public String actionCon;
    public BluetoothCommunThread communThread;
    private BroadcastReceiver controlReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            actionCon = intent.getAction();

            //如果匹配成功
            if (BluetoothTools.ACTION_PAIRING_SUCC.equals(actionCon)) {
                Bundle mBundle = intent.getExtras();
                BluetoothDevice mBluetoothDevice = mBundle.getParcelable("Pairing_Succ");
                SharedPreferences sharedPreferences = getSharedPreferences("connected_device", MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putString("addr", mBluetoothDevice.getAddress());
                editor.putString("name", mBluetoothDevice.getName());
                editor.commit();
                BluetoothClientConnThread mThread = new BluetoothClientConnThread(handler, mBluetoothDevice);
                mThread.start();
            }

            if (BluetoothTools.ACTION_BLUETOOTH_START.equals(actionCon)) {
                BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
                if (bluetoothAdapter.isEnabled()) {
                    getBondedDevice();
                } else {
                    bluetoothAdapter.enable();
                }
            }

            //蓝牙状态变化 打开

            if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(actionCon)) {
                int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
                        BluetoothAdapter.ERROR);
                if (state == BluetoothAdapter.STATE_ON) {
                    getBondedDevice();
                }
            }
            //如果键盘点击send发送数据
            if (BluetoothTools.ACTION_DATA_TO_GAME.equals(actionCon)) {

                try {
                    String editData = (String) intent.getExtras().get("editViewData");

                    byte[] bytes = editData.getBytes("gbk");
                    communThread.write(bytes);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

            }
        }
    };


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    /**
     * Service创建时的回调函数
     */
    @Override
    public void onCreate() {
        //controlReceiver的IntentFilter
        IntentFilter controlFilter = new IntentFilter();
        controlFilter.addAction(BluetoothTools.ACTION_PAIRING_SUCC);
        controlFilter.addAction(BluetoothTools.ACTION_DATA_TO_GAME);
        controlFilter.addAction(BluetoothTools.ACTION_BLUETOOTH_START);
        controlFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        //注册BroadcastReceiver
        registerReceiver(controlReceiver, controlFilter);
        super.onCreate();
    }

    private void getBondedDevice() {
        Set<BluetoothDevice> bondedDevices = BluetoothAdapter.getDefaultAdapter().getBondedDevices();
        SharedPreferences sharedPreferences = getSharedPreferences("connected_device", MODE_PRIVATE);
        String add = sharedPreferences.getString("addr", "");
        String name = sharedPreferences.getString("name", "");
        BluetoothDevice connected_bd = null;
        if (add != null && !add.equals("")) {
            for (BluetoothDevice bluetoothDevice : bondedDevices) {
                if (add.equals(bluetoothDevice.getAddress())) {
                    connected_bd = bluetoothDevice;
                }
            }
        }

        if (connected_bd == null) {
            Intent intent = new Intent(BluetoothTools.ACTION_BLUETOOTH_NO_BONDED_DEVICE);
            sendBroadcast(intent);
        } else {
            Intent intent = new Intent(BluetoothTools.ACTION_BLUETOOTH_CONNECTING);
            intent.putExtra("name", name);
            sendBroadcast(intent);
            BluetoothClientConnThread mThread = new BluetoothClientConnThread(handler, connected_bd);
            mThread.start();
        }

    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                //子线程socket连接成功
                case BluetoothTools.MESSAGE_CONNECT_SUCCESS: {
                    BluetoothSocket bluetoothSocket = (BluetoothSocket) msg.obj;
                    BluetoothDevice bluetoothDevice = bluetoothSocket.getRemoteDevice();
                    Intent mIntent = new Intent(BluetoothTools.ACTION_CONNECT_SUC);
                    mIntent.putExtra("addr", bluetoothDevice.getAddress());
                    mIntent.putExtra("name", bluetoothDevice.getName());
                    sendBroadcast(mIntent);
                    communThread = new BluetoothCommunThread(handler, bluetoothSocket);
                    communThread.start();
                    break;

                    //子线程连接错误
                }
                case BluetoothTools.MESSAGE_CONNECT_ERROR: {
                    Intent mIntent = new Intent(BluetoothTools.ACTION_CONNECT_ERROR);
                    sendBroadcast(mIntent);
                    break;

                    //子线程读取到数据
                }
                case BluetoothTools.MESSAGE_READ_OBJECT: {
                    //读取到对象
                    //发送数据广播（包含数据对象）
                    byte[] readBuf = null;
                    readBuf = (byte[]) msg.obj;
                    String ss1 = new String(readBuf, 0, msg.arg1);
                    String ss = null;
                    try {
                        ss = new String(readBuf, "gbk");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    Log.e(TAG, ss1 + "," + ss);
                    Intent recIntent = new Intent(BluetoothTools.ACTION_RECEIVE_DATA);
                    recIntent.putExtra("recData", ss);
                    sendBroadcast(recIntent);
                    break;
                }
                case BluetoothTools.MESSAGE_FILE_COMPLETED: {
                    String path = (String) msg.obj;
                    Intent recIntent = new Intent(BluetoothTools.ACTION_RECEIVE_DATA);
                    recIntent.putExtra("imagePath", path);
                    sendBroadcast(recIntent);
                    break;
                }
            }
            super.handleMessage(msg);
        }
    };


    @Override
    public void onDestroy() {
        super.onDestroy();
        communThread.cancel();
        unregisterReceiver(controlReceiver);
    }
}
